package com.xiia.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.xiia.util.CheckConstant;
import com.xiia.util.DBConnect;
import com.xiia.util.Pager;
import com.xiia.vo.Check;
import com.xiia.vo.Resource;

/**
 * @author 王书恒 2014-11-4 Resource的Dao
 */

public class ResourceDao extends BaseDao {
	private static UserDao userDao;
	private static ResourceSortDao resourceSortDao;

	public ResourceDao() {
		userDao = new UserDao();
		resourceSortDao = new ResourceSortDao();
	}

	/**
	 * 增加资源，如果成功返回Resource否则返回NULL
	 * 
	 * @param resource
	 *            资源对象
	 * @return 资源对象
	 */
	public boolean addResource(Resource r) {
		boolean b = true;
		try {
			conn = DBConnect.getConnect();
			conn.setAutoCommit(false);
			QueryRunner query = new QueryRunner();
			// 将resource写入到数据库t_reource表中
			String sql = "insert into t_resource(fileName,fileSize,filePath,addTime,resScore,status,sortId,userId)"
					+ "values(?,?,?,?,?,?,?,?)";
			Object[] p = { r.getFileName(), r.getFileSize(), r.getFilePath(),
					r.getAddTime(), r.getResScore(), r.getStatus(),
					r.getSortId(), r.getUser().getUserId() };
			query.update(conn, sql, p);
			// 2.将对应的分类的资源数量加1
			sql = "update t_resource_sort set resNum=resNum+1 where sortId=?";
			Object[] p1 = { r.getSortId() };
			query.update(conn, sql, p1);

			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				b = false;
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return b;
	}

	/**
	 * 删除资源
	 * 
	 * @param resources
	 * @return 资源集合
	 */
	public boolean deleteResource(Resource resource) {
		boolean b = true;
		try {
			conn = DBConnect.getConnect();
			conn.setAutoCommit(false);
			QueryRunner query = new QueryRunner();
		
			// 1.将resource从数据库t_reource表中删除
			String sql = "delete from t_resource where resourceId=?";
			Object[] params = { resource.getResourceId() };
			query.update(conn, sql, params);
			// 2.将对应的分类的资源数量减1
			sql = "update t_resource_sort set resNum=resNum-1 where sortId=?";
			Object[] p1 = { resource.getSortId() };
			query.update(conn, sql, p1);

			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				b = false;
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return b;
	}

	/**
	 * 修改资源
	 * 
	 * @param resource
	 * @return
	 */
	public boolean update(Resource resource) {
		String sql = "update t_resource set resScore=?,sortId=?  where resourceId=?";
		Object[] params = { resource.getResScore(), resource.getSortId(),
				resource.getResourceId() };
		int c = update(sql, params);
		if (c > 0)
			return true;
		else
			return false;
	}

	/**
	 * 通过resId得到resource对象
	 * 
	 * @param resId
	 * @return 返回resource对象
	 */
	public Resource getResourceById(int resourceId) {
		// TODO Auto-generated method stub
		String sql = "select * from t_resource where resourceId=?";
		Object[] params = { resourceId };
		Resource r = (Resource) findObject(sql, params, Resource.class);

		return r;

	}

	/**
	 * 查询得到资源分类的分页数据
	 * 
	 * @param page
	 * @param orderBy
	 * @return
	 */
	public Pager findResourcePage(Pager page, String orderBy) {
		// TODO Auto-generated method stub
		String sql = "select * from t_resource where status in(?,?) order by ? limit ?,?";
		Object[] params = {CheckConstant.STATUS_WRITE_DONE,
				CheckConstant.STATUS_CHECK_NO_PASS,
				orderBy,
				(page.getCurrentPage() - 1) * page.getPageSize(),
				page.getPageSize() };
		List<Resource> rList = find(sql, params, Resource.class);
		if (null != rList) {
			for (Resource r : rList) {
				// 封装ResourceSort
				r.setResourceSort(resourceSortDao.getResourceSortById(r
						.getSortId()));
				// 封装user
				r.setUser(userDao.getUserById(r.getUserId()));
			}
		}

		page.setList(rList);
		return page;
	}

	/**
	 * 查询得到资源的行数
	 * 
	 * @return
	 */
	public int countResource() {
		// TODO Auto-generated method stub
		String sql = "select count(resourceId) count from t_resource";
		return getCountFromTable(sql, null);
	}
	/**
	 * 申请审核
	 * @param resource
	 * @return
	 */
	public boolean askCheck(Resource resource) {
		boolean b = true;
		try {
			conn = DBConnect.getConnect();
			conn.setAutoCommit(false);
			QueryRunner query = new QueryRunner();
			//1.将自己的status=2
			String sql = "update t_resource set status=? where resourceId=?";
			Object[] p1 = {resource.getStatus(),
					resource.getResourceId()};
			query.update(conn,sql,p1);
			//2.查询t_check表，查看是否是第一次申请审核
			sql = "select * from t_check where checkedId=? and type=?";
			Object[] p2 = {resource.getResourceId(),
					CheckConstant.TYPE_RESOURCE};
			Check check = (Check) query.query(conn, sql,p2,new BeanHandler(Check.class));
			if(null != check){
				//说明不是第一次申请
				sql = "update t_check set flag=? where checkedId=? and type=?";
				Object[] p3 = {CheckConstant.FLAG_NO_CHECK,
						resource.getResourceId(),
						CheckConstant.TYPE_RESOURCE};
				query.update(conn,sql,p3);
			}else{
				//第一次申请
				sql = "insert into t_check(checkedId,type,flag) values(?,?,?)";
				Object[] p4 = {resource.getResourceId(),
						CheckConstant.TYPE_RESOURCE,
						CheckConstant.FLAG_NO_CHECK};
				query.update(conn,sql,p4);
			}
			
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				b = false;
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return b;
	}

}
